<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\Validate;
use think\facade\Request;
use think\facade\Session;
use app\model\GoodsModel;
use app\model\UserModel;
use app\model\DeptModel;
use app\model\CatModel;
use think\facade\Cache;
use app\Common;

//产品控制器
class Goods{

    //常用数据表内容 及常用字典
    var $goods=[];
    var $users =[];
    var $cats=[];
    var $status=array('1'=>'上架','2'=>'下架','3'=>'作废');
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";

    public function __construct(){
        //准备一个类型数组

        $gm=new GoodsModel();
        $this->goods = $gm->getAll();

        $um=new UserModel();
        $this->users = $um->getAll();
        $dm=new DeptModel();
        $this->depts = $dm->getAll();
        $cm=new CatModel();
        $this->cats = $cm->catTree();
        $this->sys=Db::table('sys')->find(1);
    }

    public function getImgs($imgs=''){
        if(!$imgs) return '';
        $arr = explode(",",$imgs);
        return implode(",",$arr);
    }

    //商品主页
    public function index($page=1){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $goods = new GoodsModel();

        $all = Request::param();
        $list = Db::table('goods');
        $query_arr=array(); //分页查询条件设置

        $status='';
        if(!empty($all['status'])){
            $status = $all['status'];
            $list = $list->where('status',$status);
        }

        //部门权限
        // $dept = new Dept();
        // $my_depts = $dept->getMyDepts($uid);
        // $arr =[];
        // $dept_id='';
        // foreach($my_depts as $dept){$arr[]=$dept['id'];}
        // if(!empty($all['dept_id'])){
        //     $dept_id=$all['dept_id'];
        //     if(in_array($dept_id,$arr)){
        //         $arr=[$dept_id];
        //     }else{
        //         $arr=[];
        //     }
        // }
        // $my_depts = implode(",",$arr);
        // $list->where('dept_id','in',$my_depts);

        //名称查询
        $name ='';
        if(!empty($all['name'])){
            $name = $all['name'];
            $list = $list->where('name','like','%'.$name.'%');
        }
        
        //商品类别查询
        $cat_id='';
        if(!empty($all['cat_id'])){
            $cat_id=$all['cat_id'];
            $cat_ct = new Cat();
            $sub_cats =[$cat_id];
            $sub_cats = $cat_ct->getSubCats($cat_id,$sub_cats);
            $list->where('cat_id','in',$sub_cats);
            //dump($cat_id,$sub_cats);
        }

        $list = $list->order('id')->paginate(12)->toArray();

        foreach($list['data'] as &$v){
            $v['creater_name'] =$this->users[$v['creater']]['name'];
            $v['status_name']=$this->status[$v['status']];
            $v['cat_id_name']=$this->cats[$v['cat_id']]['name'];
            $v['dept_id_name']=$this->depts[$v['dept_id']]['name'];
            $v['image']=explode(",",$v['image']);

            $tmp=[];
            foreach($v['image'] as &$img){
                if(!$img) continue;
                if($img && substr($img,0,4)!='http'){
                    $tmp[]="http://".$_SERVER['HTTP_HOST'].$img;
                }
            }
            //检查网路图片
            // if($v['other_imgs']>'111'){
            //     $v['other_imgs']= explode(";",$v['other_imgs']);
            //     foreach($v['other_imgs'] as &$img){
            //         $img=str_replace("\r\n", "", $img);
            //         if(substr($img,0,4)=='http') $tmp[]=$img;
            //     }
            //     //unset($v['other_imgs']);
            // }
            $v['image']=$tmp;

            $v['specs'] = Db::query("select id,name,storage,price,status from specs where goods_id=".$v['id']);

        }
        //halt($list);
        //处理分页其它参数
        //if($dept_id) $query_arr['dept_id']=$dept_id;
        if($cat_id) $query_arr['cat_id']=$cat_id;
        if($status) $query_arr['status']=$status;
        $query="&".http_build_query($query_arr);

        //halt($query);
        View::assign([
            'status'=>$status,
            'status_arr'=>$this->status,
            'list'=>$list,'name'=>$name,
            'cats'=>$this->cats,
            'cat_id'=>$cat_id,
            'query'=>$query,
            'currency_symbol'=>$this->sys['currency_symbol']
            ]);


        return View::fetch();

    }

    //产品编辑方法
    public function edit(){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        if(empty($all['id'])) return 'Invalid item id!'.$this->back ;

        $goods = new GoodsModel();

        //传入内容,保存数据并跳转
        if($all['id']>0 && !empty($all['name'])){
            //检测重复数据
            if($all['price']<0) return '价格错误，稍后返回！'.$this->back;

            $ex = Db::query("select * from goods where id<>? and name=?",array($all['id'],$all['name']));
            if(count($ex)) {
                return '产品名称重复!'.$this->back;
            }
            
            $all['create_time'] = date('Y-m-d H:i:s'); 

            Db::table('goods')->save($all); 
            return header('location:/index.php/goods/index/cat_id/'.$all['cat_id']);
        }
        //不传内容只有id,查出本条数据 并进入编辑
        $row = $goods->find($all['id']);
        $row['image']=explode(",",$row['image']);
        $row['dt_imgs']=explode(",",$row['dt_imgs']);

        View::assign(['data'=>$row,'cats'=>$this->cats,'user'=>$this->users[$uid]]);
        //print_r($this->cats);
        return View::fetch();
    }

    //从一个表里查询出一条数据
    public function getOne($id,$table='goods'){
        $row = Db::table($table)->find($id);
        if($row){
            return $row;
        }else{
            return [];
        }
    }

    //保存一条数据
    public function save($table='goods'){
        $all = Request::param();
        if(!$all) return 'Invalid request!'.$this->back ;

        $res = Db::table($table)->save($all);
        return $res;
    }


    //加一张图
    public function add_image(){
        $all = Request::param();
        if(!$_FILES) return 'Error!';

        if(empty($all['tb']) || empty($all['field']) || empty($all['row_id'])) return 'Error!';

        foreach($_FILES as $file){
            if($file['size']>0){
                $files =Common::upload($file);
                
                if($files['code']){
                    $row=Db::table($all['tb'])->where('id',$all['row_id'])->find();
                    if($row[$all['field']]!='') {
                        $image= $row[$all['field']].$files['msg'];
                    }else{
                        $image=$files['msg'];
                    }
                    $res = Db::table($all['tb'])->update(['id'=>$row['id'],$all['field']=>$image]);
                    return json(['code'=>$res,'msg'=>'ok']);
                }else{
                    return json(['code'=>0,'msg'=>$files['msg']]);
                }
            }
        }
    }


    public function goods_add(){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        if($all){
            if(!empty($all['id'])) return '不是一个新的商品!'.$this->back;     
            if(!$all['name']) return '无效的商品名称!'.$this->back;

            $goods = new GoodsModel();
            $row = $goods::where('name',trim($all['name']))->find();
            if(!empty($row)) return '商品已存在! ['. $all['name']."]".$this->back;

            $all['creater']  = $uid;
            $all['create_time']  = date("Y-m-d H:i:s",time());
            $all['dept_id'] = $this->users[$uid]['dept_id'];
            //$all['price1'] = $all['price']*$all['discount'];

            //halt($all,$_FILES);
            //轮播图
            foreach($_FILES as $file){
                if($file['size']>0){
                    $files =Common::upload($file);
                    
                    if($files['code']){
                        $all['image'][]=$files['msg'];
                    }else{
                        return ["code"=>0,'msg'=>"<h1>".$files['msg']."</h1>"];
                    }                       
                }
            }
            if(!empty($all['image'])) $all['image'] = implode(",",$all['image']);

            $new_id = $goods->insertGetId($all);
            $sp = array('goods_id'=>$new_id,'name'=>'标准规格','creater'=>$uid,'create_time'=>$all['create_time'],'status'=>1,'storage'=>0,'price'=>$all['price']);
            Db::table('specs')->insert($sp);
            return header("location:/goods/index");
        }

        View::assign(['cats'=>$this->cats]);
        return View::fetch();
    }

    
    //商品销售情况
    public function goods_sales(){
        $all=Request::param();

        if(empty($all['sdate'])){
            $sdate=$all['sdate']=date("Y-m-d 00:00:00",time());
        }else{
            $sdate=$all['sdate']." 00:00:00";
        }

        if(empty($all['edate'])){
            $edate=$all['edate']=date("Y-m-d 23:59:59",time());
        }else{
            $edate=$all['edate']." 23:59:59";
        }

        $group="goods_id";
        $cols="goods_id";

        if(!empty($all['group'])) {
            $cols.=",".$all['group'];
            $group.=",".$all['group'];
        }

        $sql="select ".$cols.",sum(num) as num from `order_list` where create_time between ? and ? group by ".$group;

        $list = Db::query($sql,[$sdate,$edate]);

        $num=0;
        foreach($list as &$goods){
            $num+=$goods['num'];
            $goods['name']=$this->goods[$goods['goods_id']]['name'];
            $goods['imgs']=$this->goods[$goods['goods_id']]['image'];
            if(!empty($all['group'])){
                if($all['group']=='creater'){
                    $goods['creater_name']=$this->users[$goods['creater']]['name'];
                }
            }
        }
        //dump($list);
        View::assign(['list'=>$list,'num'=>$num,'sdate'=>$sdate,'edate'=>$edate,'group'=>!empty($all['group'])?$all['group']:'']);
        return View::fetch('goods_sales');
    }


    //根据物品查出订单
    public function goods_orders(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all=Request::param();
        if(empty($all['gid'])){
            return json(array('code'=>0,'msg'=>'无效商品！'));
        }
        if(empty($all['sdate'])){
            $all['sdate']=date("Y-m-d 00:00:00",time());
        }else{
            $all['sdate'].=" 00:00:00";
        }
        if(empty($all['edate'])){
            $all['edate']=date("Y-m-d 23:59:59",time());
        }else{
            $all['edate'].=" 23:59:59";
        } 

        $sql="select order_no,creater,create_time,status,goods_list,price1 from `order` where id in(select order_id from order_list where goods_id='".$all['gid']."' and (create_time between '".$all['sdate']."' and '".$all['edate']."'))";

        $list = Db::query($sql);

        foreach($list as &$ord){
            $ord['creater_name']=$this->users[$ord['creater']]['name'];
            $ord['status_name'] =$this->ordStatus[$ord['status']];
        }
        return json($list);

    }

    //新规格
    function spec_add(){
        $uid=Session::get('logonid');
        if(!$uid) return header("location:/index.php/login/index");

        $all = Request::param();

        //保存
        if(!empty($all['save'])){
            if(!$all['name']) return json_encode(['code'=>0,'msg'=>'Error name !']);

            unset($all['save']);

            if($_FILES['file']['size']>0){
                $files =Common::upload();
                
                if($files['code']){
                    $all['imgs']=$files['msg'];
                }else{
                    return "<h1>".$files['msg']."</h1>".$this->back;
                }
            }
                
            $cat_id= DB::table('goods')->where('id',$all['goods_id'])->find();

            $res = Db::table('specs')->save($all);
            return  header('location:/index.php/goods/index/cat_id/'.$cat_id['cat_id']);
        }
        
        View::assign(['goods'=>Db::table('goods')->find($all['goods_id'])]);
        return View::fetch('spec_add');

    }

    //规格编辑
    function spec_edit(){
        $uid=Session::get('logonid');
        if(!$uid) return header("location:/index.php/login/index");

        $all = Request::param();
        if(empty($all['id'])) return json_encode(['code'=>0,'msg'=>'Access failed!']);

        //保存
        if(!empty($all['save'])){
            if(!$all['name']) return json_encode(['code'=>0,'msg'=>'Error name !']);

            unset($all['save']);
            if($_FILES['file']['size']>0){
                $files =Common::upload();
                
                if($files['code']){
                    $all['imgs']=$files['msg'];
                }else{
                    return "<h1>".$files['msg']."</h1>".$this->back;
                }
            }

            $goods=Db::query("select id,cat_id from goods where id in(select goods_id from specs where id=?)",[$all['id']]);
  
            $res = Db::table('specs')->save($all);
            return  header('location:/index.php/goods/index/cat_id/'.$goods[0]['cat_id']);
            
        }
        
        $row =Db::table('specs')->where('id',$all['id'])->select()->toArray(); 
        if(!$row) return json_encode(['code'=>0,'msg'=>'No data found!']);

        view::assign(['data'=>$row[0]]);
        return View::fetch('spec_edit');

    }

    public function goods_del(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login/target/admin');

        $all = Request::param();
        //halt($all);
        if($all){
            return Common::row_del('goods',$all['id'],'商品');
        }
        return json(['code'=>0]);
    }

    public function spec_del(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login/target/admin');

        $all = Request::param();
        //halt($all);
        if($all){
            return Common::row_del('specs',$all['id'],'商品规格');
        }
        return json(['code'=>0]);
    }


    //商城商品列表
    public function goods_list(){
        $all=Request::param();
        $list=Db::table('goods');//陪练单的特殊处理。

        if(!empty($all['name'])){
            $name = trim($all['name']);
            $list->where('name','like','%'.$name.'%');
        }

        //分类查询，需要查出所有子类下面的商品。
        if(!empty($all['cat_id'])){
            $cat_id=$all['cat_id'];
            $cat_ct = new Cat();
            $sub_cats =[];
            $sub_cats = $cat_ct->getSubCats($cat_id,$arr);
            $sub_cats[]=$cat_id;
            $list->where('cat_id','in',$sub_cats);
        }
        
        //热门商品
        if(!empty($all['hot'])){
            $list->where('hot',1);
        }

        if(!empty($all['dept_id'])){
            $list->where('dept_id',$all['dept_id']);
        }

        //排序
        if(!empty($all['sort'])){
            $all['sort']=explode("/",$all['sort']);
            if(count($all['sort'])==2){
                if($all['sort'][1]=='desc')
                    $list->order($all['sort'][0],'desc');
                else
                    $list->order($all['sort'][0],'asc');
            }

        }

        $list=$list->where('status',1)->select()->toArray();

        foreach($list as &$row){
            if($row['image']) $row['image']=explode(",",$row['image']);
            unset($row['content']);
        }

        return json($list);

    }


    //商品详情资料
    public function goods_detail(){
        $all=Request::param();
        if(empty($all['id'])) {
            return json(['code'=>0,'msg'=>'缺少商品id参数！']);
        }

        $goods = Db::table('goods')->where('id',$all['id'])->find();
        if(!$goods) return json(['code'=>0,'msg'=>'商品不存在！']);

        if(!empty($all['cat_recom'])){
            $goods['cat_recom'] = Db::table('goods')->where('id','<>',$goods['id'])->where('cat_id',$goods['cat_id'])->order('sales','desc')->limit(6)->select()->toArray();
        }

        $goods['image']=explode(",",$goods['image']); 
        $arr=[];
        foreach($goods['image'] as &$img){
            if(!$img) continue;
            if(substr($img,0,4)!='http'){
                $img="https://".$_SERVER['HTTP_HOST'].$img;
            }
            $arr[]=$img;
        }
        $goods['image']=$arr;

        $goods['dt_imgs']=explode(",",$goods['dt_imgs']);

        //检查网路图片
        if($goods['other_imgs']>'1'){
            $goods['other_imgs']= explode(";",$goods['other_imgs']);
            foreach($goods['other_imgs'] as &$img){
                $img=str_replace("\r\n", "", $img);
                if(substr($img,0,4)=='http') $goods['image'][]=$img;
            }
        }

        $goods['specs'] = Db::table('specs')->where('goods_id',$goods['id'])->where('status',1)->select()->toArray();
        foreach($goods['specs'] as &$row){
            if($row['imgs']<'111'){
                $row['imgs']=[$goods['image'][0]];
            }
        }
        
        $goods['shop_info']=Db::table('dept_info')->where('dept_id',$goods['dept_id'])->column('name,shop_img');

        return json(['code'=>1,'data'=>$goods]);
    }

    //我的收藏品
    public function favorites(){
        $all=Request::param();

        if(Session::get('logonid')=='1'){
            $list=Db::table('favorites')->where(1)->select()->toArray();
        }else{
            if(empty($all['token'])){
                return json(['code'=>0,'msg'=>'缺少token！']);
            }
            $token = new Token();
            $arr = $token->check_token($token);
            if(!$arr['code']){
                return $arr;
            }
            $customer = $arr['customer'];

            //+收藏
            if(!empty($all['goods_id'])){
                $goods=Db::table('goods')->find($all['goods_id']);
                $fav_arr=array('customer_id'=>$customer['id'],'goods_id'=>$all['goods_id'],'dept_id'=>$goods['dept_id']);
                Db::table('favorites')->save($fav_arr);
            }
            //删除
            if(!empty($all['remove_id'])){
                Db::table('favorites')->where('customer_id',$customer['id'])->where('id',$all['remove_id'])->delete();
            }

            //查询
            $list=Db::table('favorites')->where('customer_id',$customer['id'])->select()->toArray();            
        }

        foreach($list as &$v){
            $v['dept_id_name']=$this->depts[$v['dept_id']]['name'];
            $v['goods']=Db::table('goods')->find($v['goods_id']);
            $spec = Db::table('specs')->where('goods_id',$v['goods_id'])->select()->toArray();
            $v['specs'] = $spec;            
        }
    }

}
